#include "mythread.h"

// 构造函数：初始化线程，并设置 IP 地址和端口号
MyThread::MyThread(QString ip, quint16 port, QString readPath, QObject *parent)
    : QThread(parent)
{
    this->ip = ip;
    this->port = port;
    this->readPath = readPath;
}

MyThread::~MyThread()
{
    // 确保线程安全退出
    if (tcpSocket)
    {
        tcpSocket->deleteLater();
    }
}

// 线程的主函数：执行网络连接和文件传输逻辑
void MyThread::run()
{

    // 打印调试信息
    qDebug() << ip;
    qDebug() << port+1;

    // 创建 TCP 套接字，传输文件
    tcpSocket = new QTcpSocket();

    // 连接到指定的主机和端口
    tcpSocket->connectToHost(ip, port + 1);

    // 等待连接成功
    if (!tcpSocket->waitForConnected(2000))
    {
        qDebug() << "连接失败:" << tcpSocket->errorString();
        delete tcpSocket;
        emit transferFinished(false);
        return;
    }
    qDebug() << "连接成功，准备发送文件...";


    QFile file(readPath);

    if (!file.open(QIODevice::ReadOnly))
    {
        qDebug() << "打开文件失败:" << readPath;
        emit transferFinished(false);
        return;
    }

    // 发送文件内容
    qint64 totalBytes = file.size();//获取文件大小
    qint64 sentBytes = 0;
    const int bufferSize = 1024 * 1024; // 1MB缓冲区
    QByteArray buffer;

    // 循环发送文件数据
    while (!isInterruptionRequested() && sentBytes < totalBytes)
    {
        buffer = file.read(bufferSize);
        if (buffer.isEmpty())
        {
            break; // 文件读取完毕
        }

        // 发送
        if (tcpSocket->write(buffer) != buffer.size())
        {
            qDebug() << "写入数据失败:" << tcpSocket->errorString();
            file.close();
            emit transferFinished(false);
            return;
        }

        // 等待数据实际发送完成
        if (!tcpSocket->waitForBytesWritten(3000))
        {
            qDebug() << "等待写入超时:" << tcpSocket->errorString();
            file.close();
            emit transferFinished(false);
            return;
        }

        // 更新已发送字节数
        sentBytes += buffer.size();
        qDebug() << "已发送:" << sentBytes << "/" << totalBytes;

        // 计算进度
        int percent = (sentBytes * 100) / totalBytes;
        emit progressUpdated(percent); // 发送进度信号
    }

    file.close();
    tcpSocket->waitForDisconnected(2000); // 等待服务器关闭连接
    emit transferFinished(sentBytes == totalBytes);
}
